import React from "react";
import View from "../base/View";
import defaultData from "./data";
import './index.less';

export default class RatingView extends View {
  constructor(props) {
    super(props);

    this.state = {
      hoveredIndex: 0
    };
    this.onMouseOver = this.onMouseOver.bind(this);
  }

  onMouseOver(e) {
    const target = e.target;

    if(target.tagName === 'I') {
      const value = target.getAttribute('data-value');

      this.setState({
        hoveredIndex: parseInt(value)
      });
    }
  }

  formatValue(e, oldVal) {
    const target = e.target;
    const value = target.getAttribute('data-value');
    const val = parseInt(value);

    // 如果相等则表示分数置0
    return val === oldVal ? 0 : val; 
  }

  renderContent(data, value) {
    const { hoveredIndex } = this.state;
    const { score = 5, icon } = data;
    const {dataPanel} = this.props;

    return (
      <div className='rating-img-container'
        onMouseOver={this.onMouseOver}
       onMouseLeave={() => !dataPanel && this.setState({ hoveredIndex: 0 })}
      >
        {Array(score).fill(1).map((n, i) => {
          const isHighlight = hoveredIndex ? hoveredIndex > i : value > i;

          return (
            <i className={`rating-icon rating-icon-${icon} ${isHighlight ? 'highlight' : ''}`}
              data-value={i + 1}
              onClick={this.handleValueChange}
            />
          );
        })}
      </div>
    );
  }

  renderForReadonly(data, value) {
    const { score = 5, icon } = data;
    return (
      <div>
        {Array(score).fill(1).map((n, i) => {
          const isHighlight = value > i;
          return (
            <i className={`rating-icon rating-icon-${icon} ${isHighlight ? 'highlight' : ''}`}/>
          );
        })}
      </div>
    )
  }
}

RatingView.defaultProps = {
  data: defaultData,
  value: 0
};